﻿using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using xlsApplication = Microsoft.Office.Interop.Excel.Application;

namespace Conversor
{
    public class ExcelClass
    {
        #region Declarações
        public static xlsApplication XlApp;
        public static Excel.Workbook XlWorkBook;
        private static Excel.Worksheet _XlWorkSheet;
        public static string Culture;
        #endregion

        static ExcelClass()
        {
            XlApp = new xlsApplication { Visible = false, DisplayAlerts = false };
        }

        #region Abre Documento Excel

        public void OpenXls(string xls)
        {
            try
            {
                XlWorkBook = XlApp.Workbooks.Open(xls, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, false, 0, false, 1, 0);
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("80040154") != -1)//Aplicação não instalada
                {
                    MessageBox.Show("A aplicação Excel não está instalada. Não é possível exportar dados! \nA aplicação irá reiniciar.");
                    System.Windows.Forms.Application.Restart();
                }
                if (ex.Message.IndexOf("80028018") != -1)//Cultura Regional Errada
                {
                    Culture = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
                    System.Threading.Thread.CurrentThread.CurrentCulture =
                        System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

                    XlWorkBook = XlApp.Workbooks.Open(xls, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, false, 0, false, 1, 0);
                }
                else
                { MessageBox.Show(ex.Message); }
            }
        }

        #endregion

        public int xlsWorkSheet
        {
            set { _XlWorkSheet = (Excel.Worksheet)XlWorkBook.Worksheets[value]; }
        }

        public string xlsCelulas(string celulas)
        {
            return _XlWorkSheet.Cells.Range[celulas].Value2.ToString();
        }

        #region Fecha Documento Excel

        public void CloseXls(string workBook2CloseName)
        {
            Excel.Workbook workBook2Close = XlWorkBook;
            workBook2Close.Close(false, workBook2CloseName, null);
            Marshal.ReleaseComObject(workBook2Close);
        }

        #endregion
    }
}